# -*- coding:utf-8 -*-

import time
import psutil
import threading
from RWExcleIMPL import ExcelImpl


class getProcessInfo(threading.Thread):
    def __init__(self, pname, michx, secd):
        """
        :param pname: 进程NAME
        :param michx: 机器核心数，默认为8核
        :param secd: 间隔多少秒，默认为1秒
        """

        if pname == None and michx == None and secd == None:
            return ZeroDivisionError

        threading.Thread.__init__(self)

        self.michx = michx
        self.secd = secd
        self.pname = pname
        self.stopped = False
        self.ei = ExcelImpl()

        try:
            self.listproc = self.get_proc_by_name(pname)
            # self.get_cpu_info()
            # self.get_mem_info()
        except Exception as e:
            print e

    def run(self):
        while not self.stopped:
            # 获取进程的CPU信息，写入CSV中
            # print u"获取进程的CPU信息，写入CSV中"
            self.ei.write_process_info_to_csv(data=self.get_cpu_info())

            # 获取进程的内存信息，写入CSV中
            # print u"获取进程的内存信息，写入CSV中"
            self.ei.write_process_info_to_csv(datatype="mem", data=self.get_mem_info())

            time.sleep(self.secd)

    def stop(self):
        self.stopped = True

    def get_cpu_info(self):
        """
        这里的CPU使用率是根据所有的核心使用率算出的平均值
        :return: 进程CPU使用率，百分比
        """
        self.cpu_useage = [self.pname]
        for process in self.listproc:
            self.cpu_useage.append(
                str(float(process.cpu_percent() - process.cpu_percent(interval=None)) / self.michx)[0:5] + r"%")
        # print self.cpu_useage
        return self.cpu_useage

    def get_mem_info(self):
        """
        计算内存的使用率，只得出用户调用进程的使用率
        :return: 内在使用，单位M
        """
        self.mem_useage = [self.pname]
        for process in self.listproc:
            self.mem_useage.append(process.memory_full_info()[-1] / 1024 / 1024)
        # print self.mem_useage
        return self.mem_useage

    def get_proc_by_name(self, pname=None):
        """
        通过进程名称得进程对象
        :param pname: 进程名称
        :return: 进程对象
        """
        listproc = []

        for proc in psutil.process_iter():
            try:
                if proc.name().lower() == pname.lower():
                    listproc.append(proc)
                    # return proc
            except psutil.AccessDenied:
                pass
            except psutil.NoSuchProcess:
                return None
        return listproc

    def get_proc_by_id(self, pid=None):
        """
        通过进程PID得到进行的进程,扩展方法
        :param pid: 进程PID
        :return: 返回进程对象
        """
        if pid is not None:
            return psutil.Process(pid)
        else:
            return ZeroDivisionError

    def get_num_by_list(self):
        sum = 0.0
        for i in self.mem_useage:
            sum = sum + i
        avg1 = sum / len(self.mem_useage)

        listnum = self.mem_useage
        listnum.sort()

        return [listnum[0], listnum[-1], str(avg1)[0:5]]


if __name__ == '__main__':
    gpi = getProcessInfo("DeuGlobeExplorer.exe", 8, 1)
    gpi1 = getProcessInfo("DEUDBServer.exe", 8, 1)
    gpi.start()
    gpi1.start()

    print "test11111111"
    gpi.stop()
    gpi.join()
